import { get as getVal, writable, type Writable } from "svelte/store";

type AppDbml = {
  id: number;
  // app_id
  app_id: string;
  // dbml内容
  content: string;
};

type AppDbmlMap = {
  [k: string]: Writable<AppDbml>;
};

const dbmls: AppDbmlMap = {};

export const setAppDbmlSubstribe = (app_id: string, o: AppDbml) => {
  if (!dbmls[app_id]) {
    dbmls[app_id] = writable(o);
  }
  dbmls[app_id].set(o);
};

export const getAppDbmlSubstribe = (app_id: string) => {
  let v = dbmls[app_id];
  if (!v) {
    dbmls[app_id] = v = writable({ id: 0, app_id, content: "" });
  }
  return v;
};

export const hasAppDbmlSubstribe = (app_id: string) => {
  return dbmls[app_id] && getVal(dbmls[app_id]).id !== 0;
};

export const currentEditorUrl$ = writable<string>("");
export const currentDbml$ = writable<AppDbml>(null);
export const currentSql$ = writable<string>("");

export default AppDbml;
